﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using MyEFCore;

namespace MyEFCore;

public abstract class Repository<T> : IRepository<T>
    where T : class
{
    protected readonly MyDbContext _MyDbContext;

    public Repository(MyDbContext MyDbContext)
    {
        _MyDbContext = MyDbContext;
    }

    public IQueryable<T> FindAll(bool trackChanges)
    {
        return !trackChanges ? _MyDbContext.Set<T>().AsNoTracking() : _MyDbContext.Set<T>();
    }

    public IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression, bool trackChanges)
    {
        return !trackChanges
            ? _MyDbContext.Set<T>().Where(expression).AsNoTracking()
            : _MyDbContext.Set<T>().Where(expression);
    }

    public void Create(T entity)
    {
        _MyDbContext.Set<T>().Add(entity);
    }

    public void Update(T entity)
    {
        _MyDbContext.Set<T>().Update(entity);
    }

    public void Delete(T entity)
    {
        _MyDbContext.Set<T>().Remove(entity);
    }

    public int Count(Expression<Func<T, bool>> expression)
    {
        return _MyDbContext.Set<T>().Count(expression);
    }

    public int Count()
    {
        return _MyDbContext.Set<T>().Count();
    }
}
